package com.haixiaoke.callback.bill.controller;

import com.haixiaoke.saas.common.config.WeChatConfig;
import com.haixiaoke.saas.common.utils.GsonUtil;
import com.haixiaoke.saas.common.weChat.domain.ParseParam;
import com.haixiaoke.saas.common.weChat.service.WeChatService;
import com.haixiaoke.saas.common.weChat.util.WeChatUtils;
import com.haixiaoke.saas.system.framework.manager.AsyncManager;
import com.haixiaoke.saas.system.framework.manager.factory.AsyncFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author panda
 * @Date 2025/7/11
 **/
@Slf4j
@RestController
@RequestMapping("/callback/bill")
public class CallbackBillController {

    @Autowired
    private WeChatConfig weChatConfig;
    @Autowired
    private WeChatService weChatService;

    /**
     * 入住账单支付回调
     *
     * @param parseParam
     * @throws Exception
     */
    @RequestMapping("/pay")
    public String pay(@RequestBody ParseParam parseParam) {
        try {
            log.info("微信支付回调参数：{}", GsonUtil.toJson(parseParam));
            // 签名验证
            if (!weChatService.signCheck(parseParam, weChatConfig.getAccountApiKey())) {
                log.info("签名验证失败：回调的账单id：{}", parseParam.getOutTradeNo());
                return parseParam.resultFail(WeChatUtils.FAIL, "签名失败");
            }
            // 异步处理回调业务
            AsyncManager.me().execute(AsyncFactory.weChatCallbackBillPay(parseParam));
        } catch (Exception e) {
            log.error("微信支付--账单支付回调发生了错误：{}", e.getLocalizedMessage(), e);
            return parseParam.resultFail(WeChatUtils.FAIL, e.getLocalizedMessage());
        }
        return parseParam.resultSuccess();
    }
}
